<?php
class ParserController extends Controller {
 	public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(
	        /*array('allow',
	        	'actions' => array('avito', 'step1', 'update'),	
	        	'users'=>array('content'),
	        ),
	        array('deny',  // deny all users
	            'users'=>array('*'),
	        ),*/
        );
    }

    public function actionAvito () {
		$result = array();

		$model = new Home();
		
		$url = Yii::app()->request->getParam('url', false);
		$model->phone = Yii::app()->request->getParam('phone', false);
		$model->url = $url;
		
		$error = false;
		
		$model->city_id = 1;
		
		if ($url) {
			$result = array();
			$result['url']= $url;
			$copt['url'] = $url;
			$copt[CURLOPT_FOLLOWLOCATION] = 1;
			$html = MiscHelper::getContent(array($copt));
			//echo $html;
			$html = Encode::toUtf8($html[0]);
	
			// h1
			preg_match('#<h1[^\>]*?>(.*?)</h1>#si', $html, $h1);
			if (isset($h1[1])) {
				$h1 = $h1[1];
				$h1_pieces = explode(', ', $h1);
	
				switch ($h1_pieces[0])
				{
					case 'Студия': $model->type = 1; /*$result['comment'][] = 'Студия';*/ break;
					case '1-к квартира': $model->type = 1; break;
					case '2-к квартира': $model->type = 2; break;
					case '3-к квартира': $model->type = 3; break;
					case '4-к квартира': $model->type = 4; break;
					default:
						$model->type = 5;
						//$result['comment'] = 'Тип квартиры - '.$h1_pieces[0]; break;
				}
			}
			// площадь квартиры
			if (isset($h1_pieces[1])) {
				$model->area = intval($h1_pieces[1]);
			}
			// этажность
	    	if (isset($h1_pieces[2])) {
	    		$floor_pieces = explode('/', $h1_pieces[2]);
	    		if (isset($floor_pieces[0]))
					$model->floor = intval($floor_pieces[0]);
				if (isset($floor_pieces[1]))
					$model->max_floor = intval($floor_pieces[1]);
			}
	
			// цена
			preg_match('#<strong[^\>]*?itemprop=\"price\"[^\>]*?>(.*?)</strong>#si', $html, $price);
			if (isset($price[1]))
				$model->cost = intval(str_ireplace(array(' ', '\t', '&nbsp;'), '', $price[1]));
			else {
				preg_match('#<span[^\>]*?itemprop=\"price\"[^\>]*?>(.*?)</span>#si', $html, $price);
				if (isset($price[1]))
					$model->cost = intval(str_ireplace(array(' ', '\t', '&nbsp;'), '', $price[1]));
				else
					$model->cost = 0;
			}
			// картинки
			preg_match_all('#<div[^\>]*?class=\"ll[^\>]*?\">\s*?<a[^\>]*?href="(.*?)"[^\>]*?>.*?</a>\s*?</div>#si', $html, $imgs);
			$model->images = $imgs[1];
	
			foreach ($model->images as &$img) {
				$img = substr($img, 2);
				//$img = 'avito.ru'.substr($img, 1);
				//$img = '<img src="'.$img.'">';
			}
	
			// город
			preg_match('%<span[^\>]*?class=\"c-1\"[^\>]*?>(.*?)</span>%si', $html, $m);
			if (isset($m[0])) {
				$city = City::model()->find('caption=:caption', array('caption' => $m[1]));
				$model->city_id = $city->id;
			}
	
			// местоположение
			preg_match('%<div[^\>]*?itemprop=\"address\"[^\>]*?>(.*?)</div>%si', $html, $m);
	    	if (isset($m[0])) {
				if (stripos($m[0], 'i-metro') != false) {
					// есть метро
					preg_match('%<i\s+class=\"i\s+i-metro\"></i>([^,<]*?)[,|<]%si', $m[0], $ma);
					if (isset($ma[0])) {
						$metro = Metro::model()->find('caption=:caption', array('caption' => $ma[1]));
						$model->metro_id = $metro->id;
						//$result['metro'] = $ma[1];
					}
				}
				// адрес
				preg_match('%<span[^\>]*?itemprop=\"streetAddress\"[^\>]*?>(.*?)</span>%si', $html, $ma);
				if (isset($ma[0])) {
					preg_match ('#([0-9\/]+)#si', $ma[1], $maa);
					//print_r($ma); print_r($maa); die();
					// ищем номер дома	
					if (isset($maa[1])){
						$model->house = $maa[1];
						$model->street = str_ireplace(',', '', $model->street);
						$model->street = rtrim(str_ireplace($maa[1], '', $ma[1]));
					} else { // не нашли номер дома
						$model->street = $ma[1];
					}
				}
			}
	
			// описание
			preg_match('%<div[^\>]*?id=\"desc_text\"[^\>]*?>(.*?)</div>%simx', $html, $ma);
			if (isset($ma[0])){
				$model->description = $ma[1];
			}
	
			// тип дома
			preg_match('%<a[^\>]*?title=\"Тип дома\s+&mdash;\s+([^\"]*?)\"[^\>]*?>.*?</a>%si', $html, $ma);
			if (isset($ma[0])) {
				$house_type = HouseType::model()->find('type=:type', array('type' => $ma[1]));
				$model->house_type = $house_type->id;
				//$result['house_type'] = $ma[1];
			}
			//$model->district_id = 1;
			$model->isParse = 1; // avito.ru
			
			$model->status = 0;
			
			$success = $model->save();
			

			if (!$success) {
				$error = print_r($model->getErrors(), 1);
			}
		}
		
		Yii::app()->getClientScript()->registerCssFile(Yii::app()->baseUrl.'/css/gallery.css');
		
		$this->render('index',array(
			'model' => $model,
			'error' => $error,
		));
		
    }
    
    public function actionStep1()
    {	
    	$model = new Home();
    	
    	$model->city_id = 1;
    		
    	$this->render('step1',array(
    		'model'=>$model,
    	));
    }
    
	public function actionUpdate() {
    	$id = Yii::app()->request->getParam('id', -1);
    	
    	if ($id > 0) {
	    	$model = Home::model()->findByPk($id);
	    	$attr = Yii::app()->request->getParam('Home', array());
	    	
	    	if (!empty($attr)) {
	    		$model->attributes = $_POST['Home'];
	    		$model->status = 1;
	    		if ($model->save())
	    			$this->redirect(HomeController::createUrl('parser/step1'));
	    	}
	    			
	    	//$model->city_id = $city_id;
	    			
	    	$this->render('step1',array(
	    		'model'=>$model,
	    	));
    	} else {
    		throw new Exception('Ошибка сохранения квартиры');
    	}
    }
}